package com.itheima.reggie.exception;

import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
@Slf4j
@ResponseBody
@ControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {
    /**
     * 异常处理方法
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
        log.info(exception.getMessage());
        //对异常做一下处理
        String message = exception.getMessage();
        if (message.contains("Duplicate entry")){
            String[] s = message.split(" ");
            return R.error(s[2]+"账号已存在");
        }
        return R.error("未知异常");
    }

    /**
     * 根据id判断分类与菜品和套餐的关联，纯在就抛出一个异常
     * @param ex
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> CustomException(CustomException ex){
        log.info(ex.getMessage());
        return R.error(ex.getMessage());
    }
}
